from flask import Flask, url_for, render_template, request
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import redirect

import config
import datetime

app = Flask(__name__)
app.config.from_object(config.DbConfig)
db = SQLAlchemy(app)

class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    publish_office = db.Column(db.String(100), nullable=False)
    ISSN = db.Column(db.String(100), nullable=False)
    storage_time = db.Column(db.DateTime, default=datetime.datetime.now)

    def __init__(self, title, publisher, issn):
        self.title = title
        self.publish_office = publisher
        self.ISSN = issn

#db.create_all()

@app.route('/')
def index():
    books = Book.query.all()
    return render_template('index.html', bookset=books)

@app.route('/add', methods=['GET','POST'])
def add():
    if request.method == 'POST':
        title = request.form['title']
        publisher = request.form['publisher']
        issn = request.form['issn']
        print(title, publisher, issn)
        book1 = Book(title=title, publisher=publisher, issn=issn)
        db.session.add(book1)
        db.session.commit()
        return redirect(url_for('index'))
    else:
        return render_template('add.html')

@app.route('/find',methods=['POST','GET'])
def find():
    if request.method == 'POST':
        issn = request.form['issn']
        books = Book.query.filter_by(ISSN=issn).all()
        if books==[]:
            return redirect('/')
        else:
            return render_template('index.html', bookset=books)
    else:
        return redirect('/')

@app.route('/del_row', methods=['POST', 'GET'])
def del_row():
    if request.method == 'POST':
        bookid = int(request.form['bookid'])
        book = Book.query.get_or_404(bookid)
        if book != []:
            db.session.delete(book)
            db.session.commit()
    return redirect('/')

@app.route('/go_edit_row', methods=['POST', 'GET'])
def go_edit_row():
    if request.method == 'POST':
        bookid = int(request.form['bookid'])
        book = Book.query.get_or_404(bookid)
        if book == []:
            return redirect('/')
        return render_template('edit.html', book=book)
    return redirect('/')

@app.route('/edit_row', methods=['POST', 'GET'])
def edit_row():
    if request.method == 'POST':
        bookid = int(request.form['bookid'])
        book = Book.query.filter_by(id = bookid).first()
        book.title = request.form['bookname']
        book.publish_office = request.form['publisher']
        book.ISSN = request.form['issn']
        db.session.commit()
        return redirect('/')
    return redirect('/')

if __name__=='__main__':
    app.run(debug=True)
